<template>
  <scroll-view :scroll-y="true" class="h-11/12 m-auto w-11/12">
    <uni-forms :modelValue="formData">
      <!-- 校准日期及时间 -->
      <uni-card title="校准日期及时间 yyyy/mm/dd 00:00" extra="必填*">
        <uni-forms-item>
          <uni-datetime-picker
            type="datetime"
            :clear-icon="false"
            :hide-second="true"
            v-model="formData.dateTime"
            :disabled="isEdit"
          />
        </uni-forms-item>
      </uni-card>
      <!-- 温度计编号 -->
      <uni-card title="温度计编号" extra="必填*">
        <uni-forms-item>
          <uni-easyinput v-model="formData.temperatureId" :disabled="isEdit" />
        </uni-forms-item>
      </uni-card>
      <!-- 温度计使用区域 -->
      <uni-card title="温度计使用区域" extra="必填*">
        <uni-forms-item>
          <uni-easyinput
            v-model="formData.temperatureLocation"
            :disabled="isEdit"
          />
        </uni-forms-item>
      </uni-card>
      <!-- 在冰水中的实际测量温度℃/参考温度℃/参考温度与实际温度差℃（实际 - 参考） -->
      <uni-card title="在冰水中的温度" extra="必填*">
        <uni-forms-item>
          在冰水中的实际测量温度℃/参考温度℃/参考温度与实际温度差℃（实际 - 参考）
          <uni-easyinput
            type="textarea"
            v-model="formData.iceWaterTemperature"
            :disabled="isEdit"
          />
        </uni-forms-item>
      </uni-card>
      <!-- 在沸水中的实际测量温度℃/参考温度℃/参考温度与实际温度差℃（实际 - 参考） -->
      <uni-card title="在沸水中的温度" extra="必填*">
        <uni-forms-item>
          在沸水中的实际测量温度℃/参考温度℃/参考温度与实际温度差℃（实际 - 参考）
          <uni-easyinput
            type="textarea"
            v-model="formData.hotWaterTemperature"
            :disabled="isEdit"
          />
        </uni-forms-item>
      </uni-card>
      <!-- 填报人姓名 -->
      <uni-card title="填报人姓名" extra="必填*">
        <uni-forms-item>
          <uni-easyinput v-model="formData.name" :disabled="isEdit" />
        </uni-forms-item>
      </uni-card>
      <uni-card title="评语" v-show="props.id">
        <uni-easyinput v-model="reviewOpinion" />
      </uni-card>
    </uni-forms>
    <button
      @click="submitForm"
      class="mb-10 w-2/3 rounded-xl"
      style="background-color: #5199ff"
    >
      {{ submitBtnName }}
    </button>
    <ShowConfigComponent
      v-show="!isEdit"
      name="wenDuJiJiaoZhun"
      @showFormData="showFormData"
    />
  </scroll-view>
</template>

<script lang="ts" setup>
import { ref } from 'vue';
import {
  formatDate,
  compareLoadData,
  transformData,
} from '../../../utils/utils';
import { onLoad } from '@dcloudio/uni-app';
import { createTableById, showTableById, submitTable } from '@/services/write';
import type {
  FormDetail,
  returnSubmitData,
  submitTableData,
  tableDate,
} from '@/services/types/write';
import type { RequestMenuIdList } from '@/services/types/review';
import { submitMenuIdList } from '@/services/review';
import ShowConfigComponent from '@/components/ShowConfigComponent/ShowConfigComponent.vue';
// 表格提交信息
const formData = ref({
  dateTime: String(formatDate(new Date())), //校准日期及时间
  temperatureId: '', //温度计编号
  temperatureLocation: '', //温度计使用区域
  iceWaterTemperature: '', // 在冰水中的温度
  hotWaterTemperature: '', // 在沸水中的温度
  name: '', //填报人姓名
});
// 是否可编辑
const isEdit = ref(false);
// 提交按钮名字
const submitBtnName = ref('');
const props = defineProps({
  value: String,
  id: String,
});
// 评语
const reviewOpinion = ref('');
/**
 * 表格相关数据
 */
const table = () => {
  const tableData = ref<tableDate[]>([]);
  const reportingFormOperateId = ref('');
  // 如果提交按钮等于提交则创建表格
  const createTable = async () => {
    submitBtnName.value = '提交';
    // 创建表格
    uni.showLoading({
      title: '加载中...',
      mask: true,
    });
    const res = await createTableById('8286263745347911680');
    reportingFormOperateId.value = res.reportingFormOperateId;
    tableData.value = res.data;
    uni.hideLoading();
  };
  // 提交表格
  const submitNewTable = (
    reportingFormOperateId: string,
    tableData: tableDate[],
  ): submitTableData => {
    const formDetail = transformData(tableData) as FormDetail[];
    //校准日期及时间
    formDetail[0].componentValue = formData.value.dateTime;
    //温度计编号
    formDetail[1].componentValue = formData.value.temperatureId;
    //温度计使用区域
    formDetail[2].componentValue = formData.value.temperatureLocation;
    // 在冰水中的温度
    formDetail[3].componentValue = formData.value.iceWaterTemperature;
    // 在沸水中的温度
    formDetail[4].componentValue = formData.value.hotWaterTemperature;
    // 填报人姓名
    formDetail[5].componentValue = formData.value.name;
    // 其他数据
    const submitTable = ref<submitTableData>({
      formDetail: formDetail,
      reportingFormOperateId: reportingFormOperateId,
      status: 1,
      unionMenuId: '8286263745347911680',
    });

    return submitTable.value;
  };
  return {
    createTable,
    tableData,
    reportingFormOperateId,
    submitNewTable,
  };
};
const { createTable, submitNewTable, tableData, reportingFormOperateId } =
  table();
// 根据id展示数据
const showDataById = async (id: string) => {
  uni.showLoading({
    title: '加载中...',
    mask: true,
  });
  const res = await showTableById(id);
  if (res.msg === 'success') {
    //校准日期及时间
    formData.value.dateTime = res.data.formDetail[0].componentValue;
    //温度计编号
    formData.value.temperatureId = res.data.formDetail[1].componentValue;
    //温度计使用区域
    formData.value.temperatureLocation = res.data.formDetail[2].componentValue;
    // 在冰水中的温度
    formData.value.iceWaterTemperature = res.data.formDetail[3].componentValue;
    // 在沸水中的温度
    formData.value.hotWaterTemperature = res.data.formDetail[4].componentValue;
    // 填报人姓名
    if (res.data.formDetail[5]) {
      formData.value.name = res.data.formDetail[5].componentValue;
    }

    // 评语
    reviewOpinion.value = (
      res.data as returnSubmitData
    ).handleOption.reviewOpinion;
  }
  uni.hideLoading();
};
onLoad(async () => {
  // 判断提交按钮是否等于newTable，
  // 等于newTable则执行创建表格
  if (props.value === 'newTable') {
    createTable();
  } else if (props.id) {
    showDataById(props.id);
    submitBtnName.value = '审批';
    isEdit.value = true;
  }
});
// 提交
const submitForm = () => {
  uni.showModal({
    title: '确认提交？',
    content: '提交后将无法修改，请确认是否提交',
    success: function (res) {
      if (res.confirm) {
        // 等于newTable则执行提交表格
        if (props.value === 'newTable') {
          submitTable(
            submitNewTable(reportingFormOperateId.value, tableData.value),
          ).then((res) => {
            if (res.msg === 'success') {
              uni.showToast({
                title: '提交成功',
                icon: 'success',
                duration: 500,
              });
              setTimeout(() => {
                uni.navigateBack({
                  delta: 1,
                });
              }, 500);
            }
          });
        } else if (props.id) {
          // 有id意味查看详情
          const data = ref<RequestMenuIdList>({
            id: props.id,
          });
          submitMenuIdList(data.value, reviewOpinion.value).then((res) => {
            if (res.data === 'success') {
              uni.showToast({
                title: '提交成功',
                icon: 'success',
                duration: 500,
              });
              setTimeout(() => {
                uni.navigateBack({
                  delta: 1,
                });
              }, 500);
            }
          });
        }
      } else if (res.cancel) {
        console.log('用户点击取消');
      }
    },
  });
};
// 加载配置
const showFormData = (data: any) => {
  compareLoadData(formData.value, data);
};
</script>

<style lang="scss" scoped>
::v-deep.uni-card {
  .uni-card__header {
    .uni-card__header-extra {
      .uni-card__header-extra-text {
        color: #ff0000;
      }
    }
  }
}
</style>
